package com.aiden.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Cookie操作工具类
 */
public class CookieUtil {
    /**
     * 根据cookie的键获取对应的值
     *
     * @param key  键
     * @param request
     * @return
     */
    public static String getCookieVal(String key, HttpServletRequest request) {
        String val = "";
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(key)) {
                    val = cookie.getValue();
                    break;
                }
            }
        }
        return val;
    }

    /**
     * 存储cookie
     * @param key
     * @param value
     * @param response
     */
    public static void setCookieVal(String key, String value, HttpServletResponse response) {
        Cookie cookie = new Cookie(key, value);
        cookie.setHttpOnly(true);//将无法通过js脚本读取到cookie信息,一定程度提高了安全性
        response.addCookie(cookie);
    }

    /**
     * 存储cookie
     * @param key 键
     * @param value 值
     * @param expiry 有效期（以秒为单位）
     * @param response
     */
    public static void setCookieVal(String key, String value,int expiry, HttpServletResponse response) {
        Cookie cookie = new Cookie(key, value);
        cookie.setMaxAge(expiry);
        response.addCookie(cookie);
    }


    public static void removeCookie(String key, HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (int i = 0; i < cookies.length; i++) {
                if(cookies[i].getName().equals(key)){
                    cookies[i].setMaxAge(-1);
                    break;
                }
            }
        }
    }

}
